<?php
/**
 * Created by PhpStorm.
 * User: xi
 * Date: 2020-05-02
 * Time: 16:54
 */

namespace app\api\service;


use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopmeituan;
use app\admin\model\Shopmtdyprofit;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproombook;
use app\admin\model\Shopstaff;
use app\admin\model\Shoptableorder;
use app\admin\model\Userdoucode;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userwithdraw;

class DouService
{

    public function verifyCode($order)
    {

        $appKey = "awoh1q4tfg29z1yv";
        $secret = "b8976219b329b01d543e76a83c923720";
        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $appKey;
        $tokenReq["client_secret"] = $secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['data']['access_token'];


        if (substr($order['dou_code'], 0, 5) == "https") {

            $headers = get_headers($order['dou_code'], TRUE);
            $reqUrl = $headers['Location'];
            $data = parse_url($reqUrl);
            parse_str($data['query'], $results);
            $objData = $results['object_id'];
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
        } else {
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $order['dou_code'];
        }

        $preResult = $this->http_curl_get($url, $token);
        $certificates = $preResult['data']['certificates'];
        if (count($certificates) == 0) {
            return "";
        }
        $objData =  $certificates[0]['encrypted_code'];


        $shopModel = new Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();


        $poiUrl = "https://open.douyin.com/goodlife/v1/shop/poi/query/?account_id=" . $shop['dou_id'] . "&page=1&size=50";

        $poi = $this->http_curl_get($poiUrl, $token);

        //error_log("====poi==" . json_encode($poi));

        if($shop['poi_id'] != ""){
            $poi_id = $shop['poi_id'];
        }else{
            $poi_id = "";
            $obj = $poi['data']['pois'][0]['poi'];
            if(isset($obj['poi_id'])){
                $poi_id =$obj['poi_id'];
            }
            if(isset($obj['poiId'])){
                $poi_id = $obj['poiId'];
            }


        }

        //$poi_id= "7219982135754262532";

        $req = array();
        $req['verify_token'] = $order['dou_token'];
        $req['poi_id'] = $poi_id;

        $code = array();
        $code[] = $objData;
        $req['encrypted_codes'] = $code;



        $userDouModel = new Userdoucode();
        $reqUrl = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/verify/";
        $result = $this->curl_post2($reqUrl, json_encode($req), $token);


        $isChecked = 0;
        if ($result['data']['error_code'] == 0) {
            $isChecked = 1;
            $userDouModel->where('dou_code', $order['dou_code'])->update(['status' => 'used']);

            $tableOrderModel = new Shoptableorder();
            $dou_code = $result['data']['verify_results'][0]['origin_code'];
            $db = $tableOrderModel->where('order_no', $order['order_no'])->find();
            $shopMtDyModel = new Shopmtdyprofit();
            $fee = $order['amount']*$shop['ratio']/100;

            if ($db) {
                $tableOrderModel->where('id', $order['id'])->update(['dou_code' => $dou_code]);
                if($fee >0){
                    $shopMtDyModel->insert(['order_id'=>$order['id'],'shop_id'=>$order['shop_id'],'origin_amount'=>$order['amount'],'amount'=>$order['amount'],'create_time'=>time(),'type'=>'douyin','order_type'=>'tq','fee'=>$fee]);
                }

            } else {
                $shopOrderModel = new Shoporder();
                $shopOrderModel->where('id', $order['id'])->update(['dou_code' => $dou_code]);
                if($fee >0){
                    $shopMtDyModel->insert(['order_id'=>$order['id'],'shop_id'=>$order['shop_id'],'origin_amount'=>$order['amount'],'amount'=>$order['amount'],'create_time'=>time(),'type'=>'douyin','order_type'=>'qp','fee'=>$fee]);
                }

            }

        }
        return $isChecked;
    }


    public function checkCode($code)
    {

        $appKey = "awoh1q4tfg29z1yv";
        $secret = "b8976219b329b01d543e76a83c923720";
        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $appKey;
        $tokenReq["client_secret"] = $secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['data']['access_token'];

        if (substr($code, 0, 5) == "https") {

            $headers = get_headers($code, TRUE);
            $reqUrl = $headers['Location'];
            $data = parse_url($reqUrl);
            parse_str($data['query'], $results);
            $objData = $results['object_id'];
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
        } else {
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $code;
        }

        $result = $this->http_curl_get($url, $token);

        $certificates = $result['data']['certificates'];
        if (count($certificates) == 0) {
            return "";
        }

        error_log("==dou==resultdata===".json_encode($result['data']));


        return $result['data']['verify_token'];
    }


    public function orderCheckCode($code)
    {

        $appKey = "awoh1q4tfg29z1yv";
        $secret = "b8976219b329b01d543e76a83c923720";
        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $appKey;
        $tokenReq["client_secret"] = $secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['data']['access_token'];

        if (substr($code, 0, 5) == "https") {

            $headers = get_headers($code, TRUE);
            $reqUrl = $headers['Location'];
            $data = parse_url($reqUrl);
            parse_str($data['query'], $results);
            $objData = $results['object_id'];
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
        } else {
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $code;
        }

        $result = $this->http_curl_get($url, $token);

        $certificates = $result['data']['certificates'];
        if (count($certificates) == 0) {
            return "";
        }

        $payAmount = $certificates[0]['amount']['coupon_pay_amount'];
        $ret = array();
        $ret['token'] = $result['data']['verify_token'];
        $ret['price'] = $payAmount/100;
        return $ret;
    }


    //post请求
    public function curl_post($url, $postdata)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); // 解决数据包大不能提交
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    //post请求
    public function curl_post2($url, $postdata, $token)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测

        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    public function http_curl_get($url, $token)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));

        $tmpInfo = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }

}